﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TableProto;

public class EnglishTVWindow : SingletonBaseWindow<EnglishTVWindow>, IEasyAudio
{

    private const float ROTATE_SPEED = 250;
    private const float READ_WAIT_TIME = 5.0f;

    #region ui property

    public Transform _CardParent { get; set; }
    public Transform _Card1 { get; set; }
    public Transform _Card2 { get; set; }
    public Transform _Card3 { get; set; }
    public Transform _MovieRotate { get; set; }
    public Transform _EffectParent { get; set; }
    public Transform _AudioAnimation { get; set; }
    public Transform _AudioEffect { get; set; }
    public Transform _Mask { get; set; }

    public Button _Btn_Return { get; set; }
    public Button _Btn_Play { get; set; }
    public Button _Btn_Pause { get; set; }
    public Button _Btn_Audio { get; set; }

    public Text _VolumeText { get; set; }

    #endregion

    private const string EFFECT_PATH = StudyPath.effect_502003068;



    private enum EPlayModeEnum
    {
        None,
        Watch,
        Watch_Pause,
        Read,
        ReadClick,
    }

    private EPlayModeEnum m_playMode;

    private GameAudioSource m_currentAudio;

    private GameObject m_effectObj;

    private int m_timerSeq;

    private float m_audioTime;
    private float m_watchAddTime;
    private float m_watchNextTime;
    private float m_readAddTime;
    private float m_readNextTime;

    private bool isRead;

    System.Action<bool> completeCallback;
    private uint m_dataID;

    private ScrollRect3DComponent scrollComp;
    private MicAnimationCompnent m_micComp;

    protected override void OnOpen(params object[] paramArray)
    {
        base.OnOpen(paramArray);

        _CardParent.SetActive(true);
        _Btn_Play.gameObject.SetActive(true);
        _Btn_Pause.gameObject.SetActive(false);
        _Btn_Audio.gameObject.SetActive(false);
        _Mask.gameObject.SetActive(false);
        _AudioEffect.gameObject.SetActive(false);
        //_EffectParent.SetActive(false);
        //_AudioEffect.SetActive(false);
        m_micComp = _AudioAnimation.GetComponent<MicAnimationCompnent>();
        m_micComp.enabled = false;

        m_effectObj = Res.LoadObj(EFFECT_PATH);
        if (m_effectObj != null)
        {
            m_effectObj.SetLayer((int)EGameLayerMask.UI);
            m_effectObj.transform.SetParent(_AudioEffect);
            m_effectObj.transform.ResetTransformForLocal();
        }

        WindowManager.Instance.OpenWindow(WinNames.MedalPanel);
        MedalWindow.Instance.ShowXunzhang(0, false, MedalWindow.EXZCountEnum.Four);

        InitPanel();
    }

    protected override void OnUpdate()
    {
        switch (m_playMode)
        {
            case EPlayModeEnum.Watch:
                _MovieRotate.Rotate(new Vector3(0, 0, ROTATE_SPEED * Time.deltaTime));
                m_watchAddTime += Time.deltaTime;
                if (m_watchAddTime > m_watchNextTime)
                {
                    m_watchAddTime = 0;
                    if (scrollComp.CenterIndex < 3)
                    {
                        WatchNextCard();
                    }
                    else
                    {
                        OnWatchComplete();
                    }
                }
                break;

            case EPlayModeEnum.Read:
                _MovieRotate.Rotate(new Vector3(0, 0, ROTATE_SPEED * Time.deltaTime));
                m_readAddTime += Time.deltaTime;
                if (m_readAddTime > m_readNextTime)
                {
                    m_readNextTime = 10000;
                    m_readAddTime = 0;
                    if (isRead)
                    {
                        GameAudioSource audio = this.PlayAudioEx(StudyAudioName.t_32003);
                        this.AddTimerEx(audio.Length, () => {
                            ReadNextCard();
                            isRead = false;
                            m_micComp.enabled = false;
                        });
                    }
                    else
                    {
                        GameAudioSource audio = this.PlayAudioEx(StudyAudioName.t_32004);
                        this.AddTimerEx(audio.Length, () =>
                        {
                            //ResetAudioClick();
                            ReadCardFirst();
                            m_micComp.enabled = false;
                            //ReadCard();
                            isRead = true;
                        });
                    }
                }
                _VolumeText.text = MicroManager.Instance.Volume.ToString();
                if (m_micComp != null)
                {
                    m_micComp.volume = MicroManager.Instance.Volume;
                    if (m_micComp.volume > 0.4f)
                        isRead = true;
                }
                break;
        }
        
        if (scrollComp != null)
            scrollComp.OnUpdate(Time.deltaTime);
    }

    protected override void OnClose()
    {
        base.OnClose();

        _Mask.gameObject.SetActive(false);
        if (m_effectObj != null)
        {
            GameObject.Destroy(m_effectObj);
            m_effectObj = null;
        }
        if (scrollComp != null)
        {
            scrollComp.Dispose();
            scrollComp = null;
        }
        WindowManager.Instance.CloseWindow(WinNames.MedalPanel);
        MicroManager.Instance.StopRecord();
    }

    protected override void AddListeners()
    {
        _Btn_Return.onClick.AddListener(OnButtonReturnClick);
        _Btn_Play.onClick.AddListener(On_Btn_Play_Click);
        _Btn_Pause.onClick.AddListener(On_Btn_Pause_Click);
        _Btn_Audio.onClick.AddListener(On_Btn_Audio_Click);

        UIInputHandler handler = _CardParent.AddComponentEx<UIInputHandler>();
        handler.OnDown += OnCardParentDown;
        handler.OnUp += OnCardParentUp;
    }

    protected override void RemoveListensers()
    {
        _Btn_Return.onClick.RemoveAllListeners();
        _Btn_Play.onClick.RemoveAllListeners();
        _Btn_Pause.onClick.RemoveAllListeners();
        _Btn_Audio.onClick.RemoveAllListeners();

        UIInputHandler handler = _CardParent.GetComponent<UIInputHandler>();
        if (handler)
        {
            handler.OnDown += OnCardParentDown;
            handler.OnUp += OnCardParentUp;
        }
    }


    #region -------------------------- uievent

    private void OnButtonReturnClick()
    {
        if (completeCallback != null)
        {
            completeCallback(false);
        }
    }

    private void On_Btn_Play_Click()
    {
        if (_EffectParent.gameObject.activeSelf)
        {
            EventBus.Instance.BroadCastEvent(EventID.ON_ENGLISH_TV_START_PLAY);
        }
        _EffectParent.SetActive(false);
        _Btn_Pause.gameObject.SetActive(true);
        _Btn_Play.gameObject.SetActive(false);
        _AudioEffect.gameObject.SetActive(false);
        if (m_playMode == EPlayModeEnum.Watch_Pause)
        {
            ResumeWatch();
        }
        else
        {
            StartWatch();
            this.PlayAudioEx(StudyAudioName.t_31007);
        }
    }

    private void On_Btn_Pause_Click()
    {
        _Btn_Pause.gameObject.SetActive(false);
        _Btn_Play.gameObject.SetActive(true);
        PauseWatch();
    }

    private void On_Btn_Audio_Click()
    {
        if (m_playMode == EPlayModeEnum.ReadClick)
        {
            _AudioEffect.gameObject.SetActive(false);
            m_readAddTime = 0;
            m_readNextTime = READ_WAIT_TIME;
            m_playMode = EPlayModeEnum.Read;
            m_micComp.enabled = true;
            //ReadCard();
            this.PlayAudioEx(StudyAudioName.t_31007);
        }
    }

    #endregion


    public void StartGame(uint id, System.Action<bool> callback)
    {
        m_dataID = id;
        completeCallback = callback;

        InitPanel();

        _Mask.gameObject.SetActive(true);
        this.AddTimerEx(1.5f, () =>
        {
            EnglishLediAnimationWindow.Instance.PlayLediTalkAnimation(EnglishLediAnimationWindow.ELediFadeInType.BottomCenterToCenter, this.GetAudioNameEx(StudyAudioName.t_32006), ()=> {
                _Mask.gameObject.SetActive(false);
                _AudioEffect.gameObject.SetActive(true);
            });
        });
    }


    private void InitPanel()
    {
        m_playMode = EPlayModeEnum.None;
        _EffectParent.SetActive(true);
        InitScrollComp();
    }

    private void InitScrollComp()
    {
        if (scrollComp == null)
            scrollComp = new ScrollRect3DComponent();

        PictureBookPanel panel1 = _Card1.AddComponentEx<PictureBookPanel>();
        PictureBookPanel panel2 = _Card2.AddComponentEx<PictureBookPanel>();
        PictureBookPanel panel3 = _Card3.AddComponentEx<PictureBookPanel>();

        panel1.Initialize(3, m_dataID);
        panel2.Initialize(0, m_dataID);
        panel3.Initialize(1, m_dataID);

        panel2.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
        panel3.GetComponent<RectTransform>().anchoredPosition = new Vector2(panel2.GetComponent<RectTransform>().sizeDelta.x, 0);

        scrollComp.Initialize(panel1, panel2, panel3, panel2.parentRoot.position, panel3.parentRoot.position, 4, false, OnCardChangeEvent);
    }


    #region   ----------------- TV Watch


    private void StartWatch()
    {
        m_playMode = EPlayModeEnum.Watch;
        if (m_currentAudio != null)
        {
            m_currentAudio.Stop();
        }
        if (m_timerSeq != 0)
        {
            this.RemoveTimerEx(m_timerSeq);
            m_timerSeq = 0;
        }
        m_watchAddTime = 0;
        m_watchNextTime = 2;
        m_timerSeq = this.AddTimerEx(1f, () =>
        {
            m_currentAudio = PlayCurrentAudio();
            m_watchNextTime = m_currentAudio.Length + 2;
        });
    }

    private void ResumeWatch()
    {
        m_playMode = EPlayModeEnum.Watch;
        if (m_currentAudio != null)
        {
            m_currentAudio.Play(true, true);
        }
    }

    private void WatchNextCard()
    {
        scrollComp.MovePanel(EScrollEnum.LeftSlide);
    }

    private void PauseWatch()
    {
        m_playMode = EPlayModeEnum.Watch_Pause;
        if (m_currentAudio != null)
        {
            m_audioTime = m_currentAudio.Time;
            m_currentAudio.Pause();
        }
        if (m_timerSeq != 0)
        {
            this.RemoveTimerEx(m_timerSeq);
            m_timerSeq = 0;
        }
    }

    private void OnWatchComplete()
    {
        m_playMode = EPlayModeEnum.None;
        StartRead();
    }


    #endregion



    #region ---------------- TV Read

    // 点击按钮才能开始
    private void StartRead()
    {
        //m_playMode = EPlayModeEnum.Read;
        _Btn_Pause.gameObject.SetActive(false);
        _Btn_Play.gameObject.SetActive(false);
        _Btn_Audio.gameObject.SetActive(true);
        
        InitScrollComp();
        //ReadCard();

        _AudioEffect.gameObject.SetActive(false);
        _Mask.gameObject.SetActive(true);
        //this.AddTimerEx(1.5f, () =>
        //{
            EnglishLediAnimationWindow.Instance.PlayLediTalkAnimation(EnglishLediAnimationWindow.ELediFadeInType.BottomCenterToCenter, this.GetAudioNameEx(StudyAudioName.t_32007), () =>
            {
                if (!IsOpen)
                    return;
                _Mask.gameObject.SetActive(false);
                //ResetAudioClick();
                ReadCardFirst();
            });
        //});
    }

    private void ReadCardFirst()
    {
        ReadCard();
    }

    private void ResetAudioClick()
    {
        m_playMode = EPlayModeEnum.ReadClick;
        _AudioEffect.gameObject.SetActive(true);
        //this.PlayAudioEx(StudyAudioName.t_31007);
    }

    private void ReadCard()
    {
        MicroManager.Instance.StartRecord();

        m_playMode = EPlayModeEnum.None;
        if (m_currentAudio != null)
        {
            m_currentAudio.Stop();
        }
        if (m_timerSeq != 0)
        {
            this.RemoveTimerEx(m_timerSeq);
            m_timerSeq = 0;
        }
        m_timerSeq = this.AddTimerEx(1f, () =>
        {
            m_currentAudio = PlayCurrentAudio();
            m_readAddTime = 0;
            m_readNextTime = READ_WAIT_TIME;
            m_timerSeq = this.AddTimerEx(m_currentAudio.Length, () =>
            {
                //m_playMode = EPlayModeEnum.Read;
                ResetAudioClick();
                //MicroManager.Instance.StartRecord();
            });
        });
    }

    private void ReadNextCard()
    {
        //PlayGeometryAudio(StudyAudioName.sound_603020205);
        //MicroManager.Instance.StopRecord();
        MedalWindow.Instance.ShowXunzhang(scrollComp.CenterIndex + 1, true, MedalWindow.EXZCountEnum.Four, ()=>
        {
            if (scrollComp.CenterIndex < 3)
            {
                scrollComp.MovePanel(EScrollEnum.LeftSlide);
            }
            else
            {
                OnReadComplete();
            }
        });
    }

    private void OnReadComplete()
    {
        MicroManager.Instance.StopRecord();
        m_playMode = EPlayModeEnum.None;

        if (completeCallback != null)
            completeCallback(true);
    }

    #endregion





    private void OnCardParentDown()
    {
        switch (m_playMode)
        {
            case EPlayModeEnum.Watch:
                if (scrollComp != null)
                {
                    scrollComp.OnDown();
                }
                break;
        }
    }

    private void OnCardParentUp()
    {
        switch (m_playMode)
        {
            case EPlayModeEnum.Watch:
                if (scrollComp != null)
                {
                    scrollComp.OnUp();
                }
                break;
        }
    }

    private void OnCardChangeEvent(int page)
    {
        if (m_playMode == EPlayModeEnum.Watch)
        {
            StartWatch();
        }
        else if (m_playMode == EPlayModeEnum.Read)
        {
            //ResetAudioClick();
            ReadCardFirst();
            //ReadCard();
        }
    }

    private GameAudioSource PlayCurrentAudio()
    {
        string audioName = GetCurrentAudioName();

        string[] arr = audioName.Split(';');
        if (arr.Length == 2)
        {
            return this.PlayCommonAudioEx(arr[0].Trim());
        }
        else
        {
            return this.PlayEnglishAudioEx(audioName);
        }
    }

    private string GetCurrentAudioName()
    {
        if (m_dataID == 0) return "";
        EnglishLetterInfo info = FTableManager.GetEnglishLetterInfo(m_dataID);
        //info.letter_big_audio
        if (info == null)
        {
            return "";
        }
        switch (scrollComp.CenterIndex)
        {
            case 0:
                return info.game1_audio1;
            case 1:
                return info.game1_audio2;
            case 2:
                return info.game1_audio3;
            default:
                return info.game1_audio4;
        }
    }

}
